package com.qingxin.sys.service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.qingxin.sys.dao.Querier;
import com.qingxin.sys.dao.Updater;
import com.qingxin.sys.entity.LoginUser;
import com.qingxin.sys.entity.SysRole;
import com.qingxin.sys.entity.SysUser;
import com.qingxin.sys.mvc.PageParam;
import com.qingxin.sys.mvc.Pager;
import com.qingxin.sys.mvc.SysError;
import com.qingxin.sys.utils.BeanUtil;
import com.qingxin.sys.utils.StringUtils;

/**
 * 用户表
 * @author Administrator
 *
 */
@Service
public class SysUserService extends BaseService<SysUser, String> {
	
	@Autowired
	private SysUserRoleRelService sysUserRoleRelService;
	@Autowired
	private SysRoleService sysRoleService;

	
	/**
	 * 获取登录用户信息，使用spring缓存对数据进行缓存处理
	 * @param userid
	 * @return
	 */
	@Cacheable(value="userServiceCache", key="'GetLoginUser_' + #userid")
	public LoginUser getLoginUser(String userid){
		SysUser sysUser = get(userid);
		if(sysUser == null){
			return null;
		}
		LoginUser loginUser = new LoginUser(sysUser.getUserid(), sysUser.getLogin_name(),
				sysUser.getUsername(), sysUser.getPhone(), sysUser.getEmail(), sysUser.getWx_openid(),
				sysUser.getUser_type(), sysUser.getUser_status(), sysUser.getUser_kind(), sysUser.getRegionid(),
				sysUser.getPhone(), sysUser.getGroupid());
		return loginUser;
	}
	
	
	/**
	 * 清除指定用户信息缓存
	 * @param userid
	 */
	public void evictUserCache(String userid){
		evictCache("userServiceCache", "GetLoginUser_"+userid);
	}
	
	
	/**
	 * 根据登录名获取用户对象
	 * @param login_name
	 * @return
	 */
	public SysUser getUserByLoginname(String login_name){
		return getByProperty("login_name", login_name);
	}
	
	
	/**
	 * 根据手机号获取用户对象
	 * @param phone
	 * @return
	 */
	public SysUser getUserByPhone(String phone){
		return getByProperty("phone", phone);
	}
	
	/**
	 * 获取用户列表分页数据
	 * @param search
	 * @param user_type
	 * @param user_status
	 * @param regionid
	 * @param pageNo
	 * @param pageSize
	 * @param sortname
	 * @param sortorder
	 * @param request
	 * @return
	 */
	public Pager list(String groupid, String search, String user_type, String user_status, String regionid,
			PageParam pageParam, HttpServletRequest request){
		Querier querier = Querier.create("select new com.qingxin.sys.entity.SysUser(" +
				"u.userid, u.login_name, u.username, u.phone, u.email, u.user_type," +
				" u.user_status, u.user_kind, u.create_time, g.groupname)" +
				" from SysUser u, SysGroup g where u.groupid=g.groupid and u.ishide=0");
		if(StringUtils.isNotEmpty(groupid) && !"0".equals(groupid)){
			querier.append(" and u.groupid like :groupid");
			querier.setParam("groupid", groupid.replace("'", "") + "%");
		}
		if(StringUtils.isNotEmpty(user_type)){
			querier.append(" and u.user_type=:user_type");
			querier.setParam("user_type", user_type);
		}
		if(StringUtils.isNotEmpty(user_type)){
			querier.append(" and u.user_status=:user_status");
			querier.setParam("user_status", user_status);
		}
		if(StringUtils.isNotEmpty(regionid)){
			querier.append(" and u.regionid like :regionid");
			querier.setParam("regionid", regionid+"%");
		}
		if(StringUtils.isNotEmpty(search)){
			search = "%"+search.replace("'", "")+"%";
			querier.append(" and (u.login_name like :login_name or u.username like :username or u.phone like :phone)");
			querier.setParam("login_name", search);
			querier.setParam("username", search);
			querier.setParam("phone", search);
		}
		
		querier.append(pageParam.getOrderby(" order by u.create_time desc"));
		
		Pager pager = pageByQuerier(querier, pageParam);
		return pager;
	}
	
	
	/**
	 * 添加用户
	 * @param user
	 * @param passwd
	 * @param repasswd
	 * @param loginUser
	 * @param request
	 * @return
	 */
	public SysError add(SysUser user, String passwd, String repasswd, LoginUser loginUser, HttpServletRequest request){
		if(StringUtils.isEmpty(passwd) || !passwd.equals(repasswd)){
			return new SysError("passwd", "密码输入错误");
		}
		
		if(getByProperty("login_name", user.getLogin_name())!=null){
			return new SysError("login_name", "该账号已存在");
		}
		
		String salt = StringUtils.UUID().substring(10, 20);
		user.setSalt(salt);
		user.setPassword(StringUtils.md5(passwd+salt));
		
		Date now = new Date();
		user.setCreate_time(now);
		user.setUpdate_time(now);
		user.setCreate_by(loginUser.getLogin_name());
		user.setUpdate_by(loginUser.getLogin_name());
		
		user.setWx_openid("");
		user.setIshide(0);
		user.setRegionid("");
		user.setPhoto("");
		
		this.save(user);
		
		//设置角色
		SysRole sysRole = sysRoleService.getByProperty("role_code", "sys_role_"+user.getUser_kind());
		if(sysRole != null){
			sysUserRoleRelService.saveUserRoleRels(user.getUserid(), new String[]{sysRole.getRoleid()}, loginUser, request);
		}
		
		return null;
	}
	
	
	/**
	 * 修改用户信息
	 * @param user
	 * @param loginUser
	 * @param request
	 * @return
	 */
	public SysError update(SysUser user, LoginUser loginUser, HttpServletRequest request){
		SysUser old = getSafeEntity(user.getUserid());
		if(old == null){
			return new SysError("用户信息不存在");
		}
		String fields = "username,phone,email,user_type,user_status,user_kind,remark";
		BeanUtil.setTargetFields(old, user, fields, true);
		
		old.setUpdate_by(loginUser.getLogin_name());
		old.setUpdate_time(new Date());
		
		Updater<SysUser> updater = new Updater<>(old, fields+",update_by,update_time");
		this.update(updater);
		
		//清除缓存后重新加载
		evictUserCache(user.getUserid());
		
		return null;
	}
	
	
	/**
	 * 修改用户状态
	 * @param userids
	 * @param user_status 用户状态1:正常2:已停用
	 * @param loginUser
	 * @param request
	 * @return
	 */
	public SysError updateUser_status(String[] userids, String user_status, LoginUser loginUser, HttpServletRequest request){
		for(String userid : userids){
			SysUser user = getSafeEntity(userid);
			if(user == null){
				continue;
			}
			if(loginUser.getUserid().equalsIgnoreCase(userid)){
				return new SysError("不能修改自己的状态["+user.getLogin_name()+"]");
			}
			user.setUser_status(user_status);
			user.setUpdate_by(loginUser.getLogin_name());
			user.setUpdate_time(new Date());
			
			Updater<SysUser> updater = new Updater<>(user, "user_status,update_by,update_time");
			this.update(updater);
			
			//清除缓存后重新加载
			evictUserCache(user.getUserid());
		}
		return null;
	}
	
	
	/**
	 * 删除用户信息
	 * @param userids
	 * @param loginUser
	 * @param request
	 * @return
	 */
	public SysError delete(String[] userids, LoginUser loginUser, HttpServletRequest request){
		for(String userid : userids){
			SysUser user = getSafeEntity(userid);
			if(user == null){
				continue;
			}
			if(loginUser.getUserid().equalsIgnoreCase(userid)){
				return new SysError("不能删除自己的账号["+user.getLogin_name()+"]");
			}
			
			this.delete(user);
			
			//清除缓存后重新加载
			evictUserCache(userid);
		}
		return null;
	}
	
	
	/**
	 * 重置密码
	 * @param userid
	 * @param resetPasswd
	 * @param loginUser
	 * @param request
	 * @return
	 */
	public Object resetPassword(String userid, String resetPasswd, LoginUser loginUser, HttpServletRequest request){
		SysUser old = getSafeEntity(userid);
		if(old == null){
			return new SysError("用户信息不存在");
		}
		if(StringUtils.isEmpty(resetPasswd) || resetPasswd.length()<6){
			resetPasswd = "12345678";
		}
		
		String salt = StringUtils.UUID().substring(10, 20);
		old.setSalt(salt);
		old.setPassword(StringUtils.md5(resetPasswd+salt));
		
		old.setUpdate_by(loginUser.getLogin_name());
		old.setUpdate_time(new Date());
		
		Updater<SysUser> updater = new Updater<>(old, "salt,password,update_by,update_time");
		this.update(updater);
		
		//清除缓存后重新加载
		evictUserCache(userid);
		
		Map<String, String> map = new HashMap<String, String>();
		map.put("newpwd", resetPasswd);
		return map;
	}
	
	
	/**
	 * 修改个人信息
	 * @param user
	 * @param request
	 * @return
	 */
	public SysError updateSelf(SysUser user, HttpServletRequest request){
		SysUser old = getSafeEntity(user.getUserid());
		if(old == null){
			return new SysError("用户信息不存在");
		}
		String fields = "username,phone,email";
		BeanUtil.setTargetFields(old, user, fields, true);
		
		old.setUpdate_by(old.getLogin_name());
		old.setUpdate_time(new Date());
		
		Updater<SysUser> updater = new Updater<>(old, fields+",update_by,update_time");
		this.update(updater);
		
		//清除缓存后重新加载
		evictUserCache(user.getUserid());
		
		return null;
	}
	
	
	/**
	 * 修改密码
	 * @param userid
	 * @param passwd
	 * @param newPasswd
	 * @param newRepasswd
	 * @param request
	 * @return
	 */
	public SysError updatePassword(String userid, String passwd, String newPasswd, String newRepasswd, HttpServletRequest request){
		if(StringUtils.isEmpty(passwd) || StringUtils.isEmpty(newPasswd) || !newPasswd.equals(newRepasswd)){
			return new SysError("passwd", "密码输入错误");
		}
		SysUser old = getSafeEntity(userid);
		if(old == null){
			return new SysError("用户信息不存在");
		}
		String oldpwd = StringUtils.md5(passwd+old.getSalt());
		if(!old.getPassword().equalsIgnoreCase(oldpwd)){
			return new SysError("原密码输入错误");
		}
		
		String salt = StringUtils.UUID().substring(10, 20);
		old.setSalt(salt);
		old.setPassword(StringUtils.md5(newPasswd+salt));
		
		old.setUpdate_by(old.getLogin_name());
		old.setUpdate_time(new Date());
		
		Updater<SysUser> updater = new Updater<>(old, "salt,password,update_by,update_time");
		this.update(updater);
		
		//清除缓存后重新加载
		evictUserCache(userid);
		
		return null;
	}
	
	
	
	
	
	
}
